﻿define(function (require) {

    function handleATag(aTagItem, model) {
        var $aTagItem = $(aTagItem);
        var url = $aTagItem.attr('href');
        $aTagItem.attr('href', '#').unbind();

        $aTagItem.click(function (event) {
            if (url.indexOf('target=action') == -1)
                $.postMessage('url:' + url, '*', parent);
            else {
                $.postMessage('action:' + url, '*', parent);
            }

            event.preventDefault();
            event.stopPropagation();
        });
    };

    return Backbone.View.extend({
        //... is a list tag.
        tagName: "li",
        template: _.template($("#div_project").html()),
        events: {

        },
        initialize: function () {
            _.bindAll(this, 'render');
            this.model.bind('change', this.render);
            this.model.view = this;
        },
        render: function () {
            $(this.el).html(this.template(this.model.toJSON()));

            var workitem = this.model.get("Workitem");
            var totalCount = workitem.UnfinishedCount +
                         workitem.FinishedCount +
                         workitem.ExpiredCount;


            function getHeightPercent(uf, df) {
                return Math.floor((100 * uf / df) + 1);
            }
            if (totalCount > 0) {
                $(this.el)
                .find('.txt-workitem-unfinished')
                .height(getHeightPercent(workitem.UnfinishedCount, totalCount) + "%");
                $(this.el)
                .find('.txt-workitem-expired')
                .height(getHeightPercent(workitem.ExpiredCount, totalCount) + "%");
                $(this.el)
                .find('.txt-workitem-finished')
                .height(getHeightPercent(workitem.FinishedCount, totalCount) + "%");
            }

            if (this.model.get('DateDiff') > 0)
                $(this.el).find('.txt-diff, strong').addClass('txt-delaied');


            $(this.el).find('a.ezlink').each(function (index, item) {
                handleATag(item, this.model);
            });

            return this;
        },
        remove: function () {
            $(this.el).remove();
        },

        // Remove the item, destroy the model.
        clear: function () {

        }
    });
});